Reading layer `BAS_LIM_DEPARTAMENTO' from data source `C:\Users\Jorge Ruiz\Documents\GitHub\ce4-peru.github.io\dashboard\Limite_departamental' using driver `ESRI Shapefile'
Simple feature collection with 25 features and 4 fields
geometry type:  MULTIPOLYGON
dimension:      XY
bbox:           xmin: -203260.8 ymin: 7964769 xmax: 1190991 ymax: 9995733
epsg (SRID):    32718
proj4string:    +proj=utm +zone=18 +south +datum=WGS84 +units=m +no_defs

Casos Acumulados

Column 1

Casos

Casos / 100k hab

Column 2

Lineal

Logaritmico

Duplicación

Column 3

Acumulados - Lineal

Acumulados - Logaritmico

Casos Nuevos

Column 1

Casos nuevos

Column 2

Diario y media móvil - Lineal

Media Móvil - logarítmica

Duplicación de la media móvil

Column 3

Lineal

Logaritmica

Fallecidos

Column 1

Column 1

Column 1

Fallecidos Nuevos

Diagnósticos

Diagnósticos Nuevos

---
title: "CE4 - Dashboard COVID-19"
output: 
  flexdashboard::flex_dashboard:
    orientation: columns
    vertical_layout: fill
    source_code: embed
    social: menu
    theme: cosmo
    self_contained: FALSE 
    fig_mobile: TRUE
---



```{r libraries, message=F, warning=F}
library(flexdashboard)
library(rio)
library(tidyverse)
library(XML)
library(httr)
library(RCurl)
library(sf)
library(lubridate)
library(leaflet)
library(colorspace)
library(DT)
library(zoo)
library(slider)
library(plotly)
library(waffle)
library(extrafont)
library(plyr)
library(extrafont)
library(waffle)
library(RColorBrewer)
options(scipen=999)
```

```{r imports, message=F, warning=F}
nac <- rio::import("https://github.com/jincio/COVID_19_PERU/blob/master/reportes_minsa.xlsx?raw=true")

deps <- rio::import("https://github.com/jincio/COVID_19_PERU/blob/master/reportes_minsa.xlsx?raw=true", sheet = 2)

pop <- read_csv("data/peru_pop_stratum.csv") %>%
  group_by(dep_adm1) %>%
  dplyr::summarise(pop = sum(N)) %>%
  dplyr::mutate(REGION = toupper(dep_adm1))


Paises_LATAM <- c("Argentina","Bolivia","Brazil","Chile","Colombia","Ecuador","Mexico","Peru","Uruguay","Venezuela")
LATAM <- read_csv ("https://covid.ourworldindata.org/data/owid-covid-data.csv") %>%
  dplyr::filter(location %in% Paises_LATAM) %>%
  dplyr::mutate( mav_new = slide_dbl(new_cases, ~mean(.x, na.rm = TRUE), .before = 6))

shp <- st_read("Limite_departamental", stringsAsFactors = F)%>% 
  st_transform(4326) %>% 
  select(Departamento = NOMBDEP)
```


```{r DMdeps, message=F, warning=F}
c.date <- max(deps$Fecha)
y.date <- as.Date(c.date) - 1 
date <- ymd(Sys.Date())


dep <- 
  deps %>% 
  dplyr::select(dat = Fecha,
                dep = REGION, 
                pos = Positivos_totales, 
                pos.imp = PositivosImputados_totales,
                pas =Fallecidos, 
                smp =Total_muestras
                ) %>% 
  dplyr::mutate(pas = pas %>% if_else(is.na(.), 0, .)
                ) %>% 
  group_by(dep
           ) %>% 
  dplyr::mutate(pos.new = pos - lag(pos, n = 1),
                pos.imp.new = pos.imp - lag(pos.imp, n = 1),
                pas.new = lag(pas, n = 1),
                smp.new = lag(smp, n = 1),
                ratio.new = signif(pos.new/smp.new), digits = 3,
                days.start =as.numeric(dat-first(dat), unit="days"),
                days.end = difftime(date, dat , units = c("days")),
                mav.pos.new = slide_dbl(pos.new, ~mean(.x, na.rm = TRUE), .before = 6))

dep <- dep %>%
  merge(pop %>% 
          select(dep = REGION, pop)) %>% 
  mutate(pos.hab = pos/pop*100000,
         smp.hab = smp/pop*100000,
         pos.new.hab = smp/pop*100000,
         mav.pos.new.hab = mav.pos.new/pop*1000000)

geom.dep <- dep %>% merge(shp, by.y = 'Departamento', by.x = 'dep', all.x = T) %>%
  st_as_sf(sf_column_name = 'geometry') 




c.dep <- geom.dep %>%
  dplyr::filter(dat == c.date)
```



```{r, message=F, warning=F}

vars_pmav_new <- dep %>%
  dplyr::select(dat,dep,mav.pos.new.hab) %>% 
  dplyr::filter(dat == c.date) %>% 
  dplyr::arrange(dplyr::desc(mav.pos.new.hab)) %>%
  dplyr::select(dep) %>%
  dplyr::mutate(dep = ifelse(dep=="LA LIBERTAD","LA_LIBERTAD",
                                ifelse(dep=="MADRE DE DIOS","MADRE_DE_DIOS",
                                       ifelse(dep=="SAN MARTIN","SAN_MARTIN",dep))))%>% 
  .$dep

vars_mav_new <- dep %>%
  dplyr::select(dat,dep,mav.pos.new) %>% 
  dplyr::filter(dat == c.date) %>% 
  dplyr::arrange(dplyr::desc(mav.pos.new)) %>%
  dplyr::select(dep) %>%
  dplyr::mutate(dep = ifelse(dep=="LA LIBERTAD","LA_LIBERTAD",
                                ifelse(dep=="MADRE DE DIOS","MADRE_DE_DIOS",
                                       ifelse(dep=="SAN MARTIN","SAN_MARTIN",dep))))%>% 
  .$dep
```


```{r, message=F, warning=F}
nac1 <- nac %>%
  dplyr::mutate(RapidasPositivos = replace_na(RapidasPositivos,0),
                Descartados = replace_na(Descartados,0),
                PruebasRapidas = replace_na(PruebasRapidas,0),
                total_pos = Positivos + RapidasPositivos,
                pos_new = total_pos -lag(total_pos,default = 0),
                rapid_des = PruebasRapidas - RapidasPositivos,
                total_des = rapid_des + Descartados,
                des_new = total_des-lag(total_des,default = 0),
                Dia = ymd(Dia)) %>%
  dplyr::select(Dia,
                pos_new,
                des_new) %>%
  dplyr::mutate(cum_pos = cumsum(pos_new),
                tot_pruebas = pos_new+des_new,
                tm = difftime(date, Dia , units = c("days")))


nac3 <- nac1 %>%
  dplyr::mutate(new_cases = cum_pos - lag(cum_pos, default = 0),
                mav_new = slide_dbl(new_cases, ~mean(.x, na.rm = TRUE), .before = 6),
                max = max(mav_new)
  )

nac4 <- nac1 %>%
  dplyr::mutate(dias = as.numeric(Dia-first(Dia), unit="days"),
                calc = dias+20,
                dup_1 = exp((log(2)/1)*dias),
                dup_2 = exp((log(2)/2)*dias),
                dup_3 = exp((log(2)/3)*dias),
                dup_4 = exp((log(2)/4)*dias),
                mav_new = slide_dbl(pos_new, ~mean(.x, na.rm = TRUE), .before = 6)
  )

```


Casos Acumulados {.bg}
=====================================  

Column 1 {.tabset data-width=350} 
-------------------------------------

### Casos

```{r, message=F, warning=F}
labels.total <-  sprintf(
  "%s
Casos: %s", c.dep$dep, c.dep$pos) %>% lapply(htmltools::HTML) pal.cases <- colorNumeric( palette="RdPu", domain = log(c.dep$pos), na.color="transparent") leaflet(c.dep) %>% addTiles(urlTemplate = 'http://a.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png', options = providerTileOptions(minZoom = 5, maxZoom = 6)) %>% addPolygons(fillColor = pal.cases(log(c.dep$pos)), weight = 2, opacity = 1, color = "white", dashArray = "", fillOpacity = 0.7, highlight = highlightOptions( weight = 5, color = "#666", dashArray = "", fillOpacity = 0.7, bringToFront = TRUE), label = labels.total, labelOptions = labelOptions( style = list("font-weight" = "normal", padding = "3px 8px"), textsize = "15px", direction = "auto")) %>% addLegend("bottomleft", pal = pal.cases, values = log(c.dep$pos), title= 'Casos', labFormat = labelFormat(transform = function(x) round(exp(x))))%>% setMaxBounds(lng1 = -90.648918, lat1 = 4.991423, lng2 = -59.605965, lat2 = -23.920121) ``` ### Casos / 100k hab ```{r, message=F, warning=F} labels.pos.hab <- sprintf( "%s
Casos/100k hab: %s", c.dep$dep, round(c.dep$pos.hab)) %>% lapply(htmltools::HTML) pal.pos.hab <- colorNumeric( palette="RdPu", domain = log(c.dep$pos.hab), na.color="transparent") leaflet(c.dep) %>% addTiles(urlTemplate = 'http://a.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png', options = providerTileOptions(minZoom = 5, maxZoom = 6)) %>% addPolygons(fillColor = pal.pos.hab(log(c.dep$pos.hab)), weight = 2, opacity = 1, color = "white", dashArray = "", fillOpacity = 0.7, highlight = highlightOptions( weight = 5, color = "#666", dashArray = "", fillOpacity = 0.7, bringToFront = TRUE), label = labels.pos.hab, labelOptions = labelOptions( style = list("font-weight" = "normal", padding = "3px 8px"), textsize = "15px", direction = "auto")) %>% addLegend("bottomleft", pal = pal.pos.hab, values = log(c.dep$pos.hab), title= 'Casos', labFormat = labelFormat(transform = function(x) round(exp(x))))%>% setMaxBounds(lng1 = -90.648918, lat1 = 4.991423, lng2 = -59.605965, lat2 = -23.920121) ``` Column 2 {.tabset data-width=350} ------------------------------------- ### Lineal ```{r, message=F, warning=F} plot_ly(nac1) %>% add_trace(x = ~Dia, y = ~pos_new, type = 'bar', name = 'Casos Nuevos', marker = list(color = '#006b7d'), text = paste(nac1$tm, "días desde hoy"), hovertemplate = paste('Fecha: %{x}', '
Nuevos Casos: %{y}
', '%{text}'))%>% add_trace(x = ~Dia, y = ~cum_pos, type = 'scatter', mode = 'lines+markers', name = 'Casos Acumulados', yaxis = 'y2', line = list(color = '#ffa600'), marker = list(color = '#ffa600'), text = paste(nac1$tm, "días desde hoy"), hovertemplate = ~paste('Fecha: %{x}', "
Casos Acumulados: %{y:.0f}
", '%{text}')) %>% add_segments(x = "2020-04-08", xend = "2020-04-08", y = 0, yend=max(nac1$pos_new), text="2020-04-08",name="Inicio de P.R's", hovertemplate = paste('%{text}'), legendgroup = 'group2', width=2, line = list(color = "#7aa82a", width = 3, dash = "dot") )%>% layout(title = 'Casos nuevos y acumulados - Perú', titlefont=list(color="white"), xaxis = list(title = "Fecha de Reporte", color = "white"), yaxis = list(side = 'left', title = 'Casos Nuevos por día (lineal)', showgrid = FALSE, zeroline = FALSE, color = "white"), yaxis2 = list(side = 'right', overlaying = "y", title = 'Casos acumulados por día (lineal)', showgrid = FALSE, zeroline = FALSE, color = "white"), legend = list(orientation = "h", xanchor = "center", yanchor = "bottom", x = 0.5, y = -0.125, font = list(color = "white")), paper_bgcolor="black", plot_bgcolor="black", hovermode = "closest", hoverdistance = 50, dragmode="pan", margin = list(l=65, r=65, b=40, t=50), autosize=T ) %>% config(locale = "es", displaylogo=F, modeBarButtonsToRemove = c("select2d","zoom2d","lasso2d", "drawclosedpath","drawopenpath", "hoverClosestCartesian","hoverCompareCartesian", "toggleHover","toggleSpikelines"), responsive = T ) ``` ### Logaritmico ```{r, message=F, warning=F} plot_ly(nac1) %>% add_trace(x = ~Dia, y = ~pos_new, type = 'bar', name = 'Casos Nuevos', marker = list(color = '#006b7d'), text = paste(nac1$tm, "días desde hoy"), hovertemplate = paste('Fecha: %{x}', '
Nuevos Casos: %{y}
', '%{text}'))%>% add_trace(x = ~Dia, y = ~cum_pos, type = 'scatter', mode = 'lines+markers', name = 'Casos Acumulados', yaxis = 'y2', line = list(color = '#ffa600'), marker = list(color = '#ffa600'), text = paste(nac1$tm, "días desde hoy"), hovertemplate = ~paste('Fecha: %{x}', "
Casos Acumulados: %{y:.0f}
", '%{text}')) %>% add_segments(x = "2020-04-08", xend = "2020-04-08", y = 0, yend=max(nac1$pos_new), text="2020-04-08",name="Inicio de P.R's", hovertemplate = paste('%{text}'), legendgroup = 'group2', width=2, line = list(color = "#7aa82a", width = 3, dash = "dot") ) %>% layout(title = 'Casos nuevos y acumulados - Perú', titlefont=list(color="white"), xaxis = list(title = "Fecha de reporte", color ="white"), yaxis = list(side = 'left', title = 'Casos Nuevos por día (lineal)', showgrid = FALSE, zeroline = FALSE, color="white"), yaxis2 = list(side = 'right', overlaying = "y", type = "log", title = 'Casos acumulados por día (logaritmica)', showgrid = FALSE, zeroline = FALSE, tickmode = "linear", tick0 = 0, color="white"), legend = list(orientation = "h", xanchor = "center", yanchor = "bottom", x = 0.5, y = -0.125, font = list(color = "white")), paper_bgcolor="black", plot_bgcolor="black", hovermode = "closest", hoverdistance = 50, dragmode="pan", margin = list(l=65, r=65, b=40, t=50) ) %>% config(locale = "es", displaylogo=F, modeBarButtonsToRemove = c("select2d","zoom2d","lasso2d", "drawclosedpath","drawopenpath", "hoverClosestCartesian","hoverCompareCartesian", "toggleHover","toggleSpikelines"), responsive = F ) ``` ### Duplicación ```{r, message=F, warning=F} x <- data.frame(Dia = as.Date(seq(1,30, 1)+date) ) y <- x %>% dplyr::mutate(dias = as.numeric(Dia-first(nac4$Dia), unit="days"), calc = dias+20, dup_1 = exp((log(2)/1)*dias), dup_2 = exp((log(2)/2)*dias), dup_3 = exp((log(2)/3)*dias), dup_4 = exp((log(2)/4)*dias) ) %>% bind_rows(nac4) plot_ly(y)%>% add_trace(x = ~dias, y = ~pos_new, type = 'scatter', mode = 'lines+markers', name = 'Casos Acumulados', line = list(color = '#ffa600'), marker = list(color = '#ffa600'), hovertemplate = ~paste("
Casos Acumulados: %{y:.d0}
"), legendgroup = 'group1') %>% add_trace(x = ~dias, y = ~dup_1, mode = 'lines', name = 'Casos se duplican en un (1) día', line = list(color = '#0e5871', dash = "dash", width=3.5), text = "Casos se duplican en un (1) día", hoverinfo = "text", legendgroup = 'group2') %>% add_trace(x = ~dias, y = ~dup_2, mode = 'lines', name = 'Casos se duplican en dos (2) días', line = list(color = '#006b7d', dash = "dash", width=3.5), text = "Casos se duplican en dos (2) días", hoverinfo = "text", legendgroup = 'group2') %>% add_trace(x = ~dias, y = ~dup_3, mode = 'lines', name = 'Casos se duplican en tres (3) días', line = list(color = '#007e7b', dash = "dash", width=3.5), text = "Casos se duplican en tres (3) días", hoverinfo = "text", legendgroup = 'group2') %>% add_trace(x = ~dias, y = ~dup_4, mode = 'lines', name = 'Casos se duplican en cuatro (4) días', line = list(color = '#008f6a', dash = "dash", width=3.5), text = "Casos se duplican en tres (4) días", hoverinfo = "text", legendgroup = 'group2') %>% layout(title = 'Total de casos acumulados desde el inicio de los casos', titlefont=list(color="white"), xaxis = list(title = "Días desde el primer reporte", range = c(min(0),max(nac4$calc)+5), color ="white"), yaxis = list(side = 'left', title = 'Total de casos acumulados', type="log", range = c(min(0),max(6)), showgrid = FALSE, zeroline = FALSE, tickmode = "linear", tick0 = 0, color ="white"), legend = list(orientation = "h", xanchor = "center", yanchor = "bottom", x = 0.5, y = -0.25, font = list(color = "white")), paper_bgcolor="black", plot_bgcolor="black", hovermode = "closest", hoverdistance = 50, dragmode="pan", margin = list(l=50, r=50, b=30, t=50) ) %>% config(locale = "es", displaylogo=F, modeBarButtonsToRemove = c("select2d","zoom2d","lasso2d", "drawclosedpath","drawopenpath", "hoverClosestCartesian","hoverCompareCartesian", "toggleHover","toggleSpikelines") ) ``` Column 3 {.tabset data-width=350} ------------------------------------- ### Acumulados - Lineal ```{r, message=F, warning=F} last <- vars_mav_new[length(vars_mav_new)] x <- dep %>% select(dat,dep,pos) %>% spread(dep, pos) %>% mutate(tm = difftime(date, dat , units = c("days"))) %>% dplyr::rename(LA_LIBERTAD = `LA LIBERTAD`, MADRE_DE_DIOS = `MADRE DE DIOS`, SAN_MARTIN = `SAN MARTIN`) ``` ```{r, message=F, warning=F} plots <- lapply(vars_mav_new, function(var) { last <- vars_mav_new[length(vars_mav_new)] plot_ly(x) %>% add_lines(x = ~dat, y = as.formula(paste0("~", var)), text = paste(x$tm, "días desde hoy"), hovertemplate = paste('Fecha: %{x}', '
Media Móvil: %{y:.2f}
', '%{text}'), name = ifelse(var == last,"Media Móvil",var), legendgroup = 'group1', showlegend = ifelse(var == last,TRUE,FALSE), line = list(color = "#ffa600", width = 4) ) %>% add_segments(x = "2020-04-08", xend = "2020-04-08", y = 0, yend = max(x[var],na.rm = T), text="2020-04-08", name="Inicio de P.R's", hovertemplate = paste('%{text}'), legendgroup = 'group2', showlegend = ifelse(var == last,TRUE,FALSE), line = list(color = "#7aa82a", width = 3, dash = "dot") ) %>% layout(xaxis = list(range = c(min(x$dat), max(x$dat)), color = "white"), yaxis = list(color = "white"), annotations = list(text = ifelse(var=="LA_LIBERTAD","LA LIBERTAD", ifelse(var=="MADRE_DE_DIOS","MADRE DE DIOS", ifelse(var=="SAN_MARTIN","SAN MARTIN",paste0("",var,"")))), x = 0,y = 1.15, yref = "paper",xref = "paper", xanchor = "left",yanchor = "top", showarrow = FALSE, font = list(size = 16, color = "white")), paper_bgcolor="black", plot_bgcolor="black", legend = list(orientation = "h", xanchor = "center", yanchor = "bottom", x = 0.5, y = -0.125, font = list(color = "white")), showlegend =T) }) subplot(plots,nrows=5, shareX = T, titleX = F) %>% layout(title = list(text = "Total de casos confirmados - Acumulado Lineal", font = list(size = 24, color="white")), annotations = list( list(text = "Fecha de reporte", x = 0.5, y = -0.09, yref = "paper", xref = "paper", showarrow = FALSE, font = list(size = 16, color = "white")), list(text = "Total de casos confirmados", x = -0.05, y = 0.5, yref = "paper", xref = "paper", showarrow = FALSE, font = list(size = 16, color ="white"), textangle = -90)), hovermode = "closest", hoverdistance = 10, dragmode="pan", margin = list(l=75, r=0, b=65, t=60) ) %>% config(locale = "es", displaylogo=F, modeBarButtonsToRemove = c("select2d","zoom2d","lasso2d", "drawclosedpath","drawopenpath", "hoverClosestCartesian","hoverCompareCartesian", "toggleHover","toggleSpikelines") ) ``` ### Acumulados - Logaritmico ```{r, message=F, warning=F} plots <- lapply(vars_mav_new, function(var) { last <- vars_mav_new[length(vars_mav_new)] plot_ly(x) %>% add_lines(x = ~dat, y = as.formula(paste0("~", var)), text = paste(x$tm, "días desde hoy"), hovertemplate = paste('Fecha: %{x}', '
Media Móvil: %{y:.2f}
', '%{text}'), name = ifelse(var == last,"Media Móvil",var), legendgroup = 'group1', showlegend = ifelse(var == last,TRUE,FALSE), line = list(color = "#ffa600", width = 4) ) %>% add_segments(x = "2020-04-08", xend = "2020-04-08", y = 0, yend = max(x[var],na.rm = T), text="2020-04-08", name="Inicio de P.R's", hovertemplate = paste('%{text}'), legendgroup = 'group2', showlegend = ifelse(var == last,TRUE,FALSE), line = list(color = "#7aa82a", width = 3, dash = "dot") ) %>% layout(xaxis = list(range = c(min(x$dat), max(x$dat)), color = "white"), yaxis = list(color = "white", type = "log", tickmode = "linear"), annotations = list(text = ifelse(var=="LA_LIBERTAD","LA LIBERTAD", ifelse(var=="MADRE_DE_DIOS","MADRE DE DIOS", ifelse(var=="SAN_MARTIN","SAN MARTIN",paste0("",var,"")))), x = 0,y = 1.15, yref = "paper",xref = "paper", xanchor = "left",yanchor = "top", showarrow = FALSE, font = list(size = 16, color = "white")), paper_bgcolor="black", plot_bgcolor="black", legend = list(orientation = "h", xanchor = "center", yanchor = "bottom", x = 0.5, y = -0.125, font = list(color = "white")), showlegend =T) }) subplot(plots,nrows=5, shareX = T, titleX = F) %>% layout(title = list(text = "Total de casos confirmados - Acumulado Logarítmico", font = list(size = 24, color="white")), annotations = list( list(text = "Fecha de reporte", x = 0.5, y = -0.09, yref = "paper", xref = "paper", showarrow = FALSE, font = list(size = 16, color = "white")), list(text = "Total de casos confirmados", x = -0.05, y = 0.5, yref = "paper", xref = "paper", showarrow = FALSE, font = list(size = 16, color ="white"), textangle = -90)), hovermode = "closest", hoverdistance = 10, dragmode="pan", margin = list(l=75, r=0, b=65, t=60) ) %>% config(locale = "es", displaylogo=F, modeBarButtonsToRemove = c("select2d","zoom2d","lasso2d", "drawclosedpath","drawopenpath", "hoverClosestCartesian","hoverCompareCartesian", "toggleHover","toggleSpikelines") ) ``` Casos Nuevos {.bg} ===================================== Column 1 {.tabset data-width=350} ------------------------------------- ### Casos nuevos ```{r, message=F, warning=F} labels.new <- sprintf( "%s
Casos: %s", c.dep$dep, c.dep$pos.new) %>% lapply(htmltools::HTML) pal.newcases <- colorNumeric( palette="RdPu", domain = log(c.dep %>% dplyr::mutate(pos.new = ifelse(pos.new==0,NA, pos.new)) %>% .$pos.new), na.color="transparent") leaflet(c.dep) %>% addTiles(urlTemplate = 'http://a.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png', options = providerTileOptions(minZoom = 5, maxZoom = 6)) %>% addPolygons(fillColor = pal.newcases(log(c.dep$pos.new)), weight = 2, opacity = 1, color = "white", dashArray = "", fillOpacity = 0.7, highlight = highlightOptions( weight = 5, color = "#666", dashArray = "", fillOpacity = 0.7, bringToFront = TRUE), label = labels.new, labelOptions = labelOptions( style = list("font-weight" = "normal", padding = "3px 8px"), textsize = "15px", direction = "auto")) %>% addLegend("bottomleft", pal=pal.newcases, values = log(c.dep$pos.new), title= 'Casos', labFormat = labelFormat(transform = function(x) round(exp(x))))%>% setMaxBounds(lng1 = -90.648918, lat1 = 4.991423, lng2 = -59.605965, lat2 = -23.920121) ``` Column 2 {.tabset data-width=350} ------------------------------------- ### Diario y media móvil - Lineal ```{r, message=F, warning=F} plot_ly(nac3) %>% add_trace(x = ~Dia, y = ~pos_new, type = 'scatter', mode = 'lines', name = 'Casos Nuevos por día', line = list(color = '#006b7d'), text = paste(nac3$tm, "días desde hoy"), hovertemplate = paste('Fecha: %{x}', '
Nuevos Casos: %{y}
', '%{text}'))%>% add_trace(x = ~Dia, y = ~mav_new, type = 'scatter', mode = 'lines+markers', name = 'Media Móvil de casos por día', line = list(color = '#ffa600'), marker = list(color = '#ffa600'), text = paste(nac3$tm, "días desde hoy"), hovertemplate = ~paste('Fecha: %{x}', "
Media móvil: %{y:.0f}
", '%{text}')) %>% add_segments(x = "2020-04-08", xend = "2020-04-08", y = 0, yend=max(nac3$pos_new), text="2020-04-08",name="Inicio de P.R's", hovertemplate = paste('%{text}'), legendgroup = 'group2', width=2, line = list(color = "#7aa82a", width = 3, dash = "dot") )%>% layout(title = ' Casos nuevos por día y media móvil', titlefont=list(color="white"), xaxis = list(title = "Fecha de reporte", color="white"), yaxis = list(side = 'left', title = 'Casos nuevos por día', showgrid = FALSE, zeroline = FALSE, color = "white"), yaxis2 = list(side = 'right', overlaying = "y", title = 'Casos nuevos (lineal)', showgrid = FALSE, zeroline = FALSE, color="#ffa600", range = c(min(0), max(nac3$pos_new))), legend = list(orientation = "h", xanchor = "center", yanchor = "bottom", x = 0.5, y = -0.15, font = list(color = "white")), paper_bgcolor="black", plot_bgcolor="black", hovermode = "closest", hoverdistance = 50, dragmode="pan", margin = list(l=65, r=0, b=40, t=50) ) %>% config(locale = "es", displaylogo=F, modeBarButtonsToRemove = c("select2d","zoom2d","lasso2d", "drawclosedpath","drawopenpath", "hoverClosestCartesian","hoverCompareCartesian", "toggleHover","toggleSpikelines") ) ``` ### Media Móvil - logarítmica ```{r, message=F, warning=F} plot_ly(nac3) %>% add_trace(x = ~Dia, y = ~pos_new, type = 'scatter', mode="lines",name = 'Casos Nuevos', line = list(color = '#006b7d'), text = paste(nac3$tm, "días desde hoy"), hovertemplate = paste('Fecha: %{x}', '
Nuevos Casos: %{y}
', '%{text}'))%>% add_trace(x = ~Dia, y = ~mav_new, type = 'scatter', mode = 'lines+markers', name = 'Media Móvil', line = list(color = '#ffa600'), marker = list(color = '#ffa600'), text = paste(nac3$tm, "días desde hoy"), hovertemplate = ~paste('Fecha: %{x}', "
Media móvil: %{y:.0f}
", '%{text}')) %>% add_segments(x = "2020-04-08", xend = "2020-04-08", y = 0, yend=max(nac3$pos_new), text="2020-04-08",name="Inicio de P.R's", hovertemplate = paste('%{text}'), legendgroup = 'group2', width=2, line = list(color = "#7aa82a", width = 3, dash = "dot") )%>% layout(title = 'Media móvil (7d) y casos nuevos por día - Perú', titlefont=list(color="white"), xaxis = list(title = "Fecha de reporte", color="white"), yaxis = list(side = 'left', title = 'Casos nuevos por día', showgrid = FALSE, zeroline = FALSE, color = "white", type ="log"), yaxis2 = list(side = 'right', overlaying = "y", title = 'Media móvil de casos nuevos - 7 días (lineal)', showgrid = FALSE, zeroline = FALSE, color="#ffa600", range = c(min(0), max(nac3$pos_new))), legend = list(orientation = "h", xanchor = "center", yanchor = "bottom", x = 0.5, y = -0.15, font = list(color = "white")), paper_bgcolor="black", plot_bgcolor="black", hovermode = "closest", hoverdistance = 50, dragmode="pan", margin = list(l=65, r=0, b=40, t=50) ) %>% config(locale = "es", displaylogo=F, modeBarButtonsToRemove = c("select2d","zoom2d","lasso2d", "drawclosedpath","drawopenpath", "hoverClosestCartesian","hoverCompareCartesian", "toggleHover","toggleSpikelines") ) ``` ### Duplicación de la media móvil ```{r, message=F, warning=F} x <- data.frame(Dia = as.Date(seq(1,30, 1)+date) ) y <- x %>% dplyr::mutate(dias = as.numeric(Dia-first(nac4$Dia), unit="days"), calc = dias+20, dup_1 = exp((log(2)/1)*dias), dup_2 = exp((log(2)/2)*dias), dup_3 = exp((log(2)/3)*dias), dup_4 = exp((log(2)/4)*dias) ) %>% bind_rows(nac4) plot_ly(y)%>% add_trace(x = ~dias, y = ~cum_pos, type = 'scatter', mode = 'lines+markers', name = 'Casos Acumulados', line = list(color = '#ffa600'), marker = list(color = '#ffa600'), hovertemplate = ~paste("
Casos Acumulados: %{y:.d0}
"), legendgroup = 'group1') %>% add_trace(x = ~dias, y = ~dup_1, mode = 'lines', name = 'Casos se duplican en un (1) día', line = list(color = '#0e5871', dash = "dash", width=3.5), text = "Casos se duplican en un (1) día", hoverinfo = "text", legendgroup = 'group2') %>% add_trace(x = ~dias, y = ~dup_2, mode = 'lines', name = 'Casos se duplican en dos (2) días', line = list(color = '#006b7d', dash = "dash", width=3.5), text = "Casos se duplican en dos (2) días", hoverinfo = "text", legendgroup = 'group2') %>% add_trace(x = ~dias, y = ~dup_3, mode = 'lines', name = 'Casos se duplican en tres (3) días', line = list(color = '#007e7b', dash = "dash", width=3.5), text = "Casos se duplican en tres (3) días", hoverinfo = "text", legendgroup = 'group2') %>% add_trace(x = ~dias, y = ~dup_4, mode = 'lines', name = 'Casos se duplican en cuatro (4) días', line = list(color = '#008f6a', dash = "dash", width=3.5), text = "Casos se duplican en tres (4) días", hoverinfo = "text", legendgroup = 'group2') %>% layout(title = 'Total de casos acumulados desde el inicio de los casos', titlefont=list(color="white"), xaxis = list(title = "Días desde el primer reporte", range = c(min(0),max(nac4$calc)+5), color ="white"), yaxis = list(side = 'left', title = 'Total de casos acumulados', type="log", range = c(min(0),max(6)), showgrid = FALSE, zeroline = FALSE, tickmode = "linear", tick0 = 0, color ="white"), legend = list(orientation = "h", xanchor = "center", yanchor = "bottom", x = 0.5, y = -0.25, font = list(color = "white")), paper_bgcolor="black", plot_bgcolor="black", hovermode = "closest", hoverdistance = 50, dragmode="pan", margin = list(l=50, r=50, b=30, t=50) ) %>% config(locale = "es", displaylogo=F, modeBarButtonsToRemove = c("select2d","zoom2d","lasso2d", "drawclosedpath","drawopenpath", "hoverClosestCartesian","hoverCompareCartesian", "toggleHover","toggleSpikelines") ) ``` ```{r, message=F, warning=F} x <- dep %>% select(dat,dep,mav.pos.new) %>% spread(dep, mav.pos.new) %>% mutate(tm = difftime(date, dat , units = c("days"))) %>% dplyr::rename(LA_LIBERTAD = `LA LIBERTAD`, MADRE_DE_DIOS = `MADRE DE DIOS`, SAN_MARTIN = `SAN MARTIN`) y <- dep %>% #Distinto a deps2 select(dat,dep,pos.imp.new) %>% spread(dep, pos.imp.new) %>% mutate(tm = difftime(date, dat , units = c("days")))%>% dplyr::rename(LA_LIBERTAD = `LA LIBERTAD`, MADRE_DE_DIOS = `MADRE DE DIOS`, SAN_MARTIN = `SAN MARTIN`) colnames(y) <- paste(colnames(y), "2", sep = "_") x<- y %>% select(-c("dat_2")) %>% cbind(x) ``` Column 3 {.tabset data-width=350} ------------------------------------- ### Lineal ```{r, message=F, warning=F} plots <- lapply(vars_mav_new, function(var) { last <- vars_mav_new[length(vars_mav_new)] x <- dep %>% select(dat,dep,mav.pos.new) %>% spread(dep, mav.pos.new) %>% mutate(tm = difftime(date, dat , units = c("days"))) %>% dplyr::rename(LA_LIBERTAD = `LA LIBERTAD`, MADRE_DE_DIOS = `MADRE DE DIOS`, SAN_MARTIN = `SAN MARTIN`) y <- dep %>% #Distinto a deps2 select(dat,dep,pos.imp.new) %>% spread(dep, pos.imp.new) %>% mutate(tm = difftime(date, dat , units = c("days")))%>% dplyr::rename(LA_LIBERTAD = `LA LIBERTAD`, MADRE_DE_DIOS = `MADRE DE DIOS`, SAN_MARTIN = `SAN MARTIN`) colnames(y) <- paste(colnames(y), "2", sep = "_") x<- y %>% select(-c("dat_2")) %>% cbind(x) plot_ly(x) %>% add_lines(x = ~dat, y = as.formula(paste0("~", var)), text = paste(x$tm, "días desde hoy"), hovertemplate = paste('Fecha: %{x}', '
Media Móvil: %{y:.2f}
', '%{text}'), name = ifelse(var == last,"Media Móvil",var), legendgroup = 'group1', showlegend = ifelse(var == last,TRUE,FALSE), line = list(color = "#ffa600", width = 4) ) %>% add_segments(x = "2020-04-08", xend = "2020-04-08", y = 0, yend = max(y[paste0(var,"_2")],na.rm = T), text="2020-04-08", name="Inicio de P.R's", hovertemplate = paste('%{text}'), legendgroup = 'group2', showlegend = ifelse(var == last,TRUE,FALSE), line = list(color = "#7aa82a", width = 3, dash = "dot") )%>% add_trace(x = ~dat, y = as.formula(paste0("~", var,"_2")), type = 'bar', name = 'Casos Nuevos', marker = list(color = '#006b7d'), text = paste(x$tm, "días desde hoy"), hovertemplate = paste('Fecha: %{x}', '
Nuevos Casos: %{y}
', '%{text}'), showlegend = ifelse(var == last,TRUE,FALSE)) %>% layout(xaxis = list(range = c(min(x$dat), max(x$dat)), color = "white"), yaxis = list(color = "white"), annotations = list(text = ifelse(var=="LA_LIBERTAD","LA LIBERTAD", ifelse(var=="MADRE_DE_DIOS","MADRE DE DIOS", ifelse(var=="SAN_MARTIN","SAN MARTIN",paste0("",var,"")))), x = 0,y = 1.15, yref = "paper",xref = "paper", xanchor = "left",yanchor = "top", showarrow = FALSE, font = list(size = 16, color = "white")), paper_bgcolor="black", plot_bgcolor="black", legend = list(orientation = "h", xanchor = "center", yanchor = "bottom", x = 0.5, y = -0.125, font = list(color = "white")), showlegend =T) }) subplot(plots,nrows=5, shareX = T, titleX = F) %>% layout(title = list(text = "Media móvil (7 días) de casos nuevos", font = list(size = 24, color="white")), annotations = list( list(text = "Fecha de reporte", x = 0.5, y = -0.09, yref = "paper", xref = "paper", showarrow = FALSE, font = list(size = 16, color = "white")), list(text = "Media móvil - Número de casos", x = -0.05, y = 0.5, yref = "paper", xref = "paper", showarrow = FALSE, font = list(size = 16, color ="white"), textangle = -90)), hovermode = "closest", hoverdistance = 10, dragmode="pan", margin = list(l=75, r=0, b=65, t=60) ) %>% config(locale = "es", displaylogo=F, modeBarButtonsToRemove = c("select2d","zoom2d","lasso2d", "drawclosedpath","drawopenpath", "hoverClosestCartesian","hoverCompareCartesian", "toggleHover","toggleSpikelines") ) ``` ### Logaritmica ```{r, message=F, warning=F} plots <- lapply(vars_mav_new, function(var) { last <- vars_mav_new[length(vars_mav_new)] x <- dep %>% select(dat,dep,mav.pos.new) %>% spread(dep, mav.pos.new) %>% mutate(tm = difftime(date, dat , units = c("days"))) %>% dplyr::rename(LA_LIBERTAD = `LA LIBERTAD`, MADRE_DE_DIOS = `MADRE DE DIOS`, SAN_MARTIN = `SAN MARTIN`) y <- dep %>% #Distinto a deps2 select(dat,dep,pos.imp.new) %>% spread(dep, pos.imp.new) %>% mutate(tm = difftime(date, dat , units = c("days")))%>% dplyr::rename(LA_LIBERTAD = `LA LIBERTAD`, MADRE_DE_DIOS = `MADRE DE DIOS`, SAN_MARTIN = `SAN MARTIN`) colnames(y) <- paste(colnames(y), "2", sep = "_") x<- y %>% select(-c("dat_2")) %>% cbind(x) plot_ly(x) %>% add_lines(x = ~dat, y = as.formula(paste0("~", var)), text = paste(x$tm, "días desde hoy"), hovertemplate = paste('Fecha: %{x}', '
Media Móvil: %{y:.2f}
', '%{text}'), name = ifelse(var == last,"Media Móvil",var), legendgroup = 'group1', showlegend = ifelse(var == last,TRUE,FALSE), line = list(color = "#ffa600", width = 4) ) %>% add_segments(x = "2020-04-08", xend = "2020-04-08", y = 0, yend = max(y[paste0(var,"_2")],na.rm = T), text="2020-04-08", name="Inicio de P.R's", hovertemplate = paste('%{text}'), legendgroup = 'group2', showlegend = ifelse(var == last,TRUE,FALSE), line = list(color = "#7aa82a", width = 3, dash = "dot") )%>% add_trace(x = ~dat, y = as.formula(paste0("~", var,"_2")), type = 'bar', name = 'Casos Nuevos', marker = list(color = '#006b7d'), text = paste(x$tm, "días desde hoy"), hovertemplate = paste('Fecha: %{x}', '
Nuevos Casos: %{y}
', '%{text}'), showlegend = ifelse(var == last,TRUE,FALSE)) %>% layout(xaxis = list(range = c(min(x$dat), max(x$dat)), color = "white"), yaxis = list(color = "white", type="log"), annotations = list(text = ifelse(var=="LA_LIBERTAD","LA LIBERTAD", ifelse(var=="MADRE_DE_DIOS","MADRE DE DIOS", ifelse(var=="SAN_MARTIN","SAN MARTIN",paste0("",var,"")))), x = 0,y = 1.15, yref = "paper",xref = "paper", xanchor = "left",yanchor = "top", showarrow = FALSE, font = list(size = 16, color = "white")), paper_bgcolor="black", plot_bgcolor="black", legend = list(orientation = "h", xanchor = "center", yanchor = "bottom", x = 0.5, y = -0.125, font = list(color = "white")), showlegend =T) }) subplot(plots,nrows=5, shareX = T, titleX = F) %>% layout(title = list(text = "Media móvil (7 días) de casos nuevos", font = list(size = 24, color="white")), annotations = list( list(text = "Fecha de reporte", x = 0.5, y = -0.09, yref = "paper", xref = "paper", showarrow = FALSE, font = list(size = 16, color = "white")), list(text = "Media móvil - Número de casos", x = -0.05, y = 0.5, yref = "paper", xref = "paper", showarrow = FALSE, font = list(size = 16, color ="white"), textangle = -90)), hovermode = "closest", hoverdistance = 10, dragmode="pan", margin = list(l=75, r=0, b=65, t=60) ) %>% config(locale = "es", displaylogo=F, modeBarButtonsToRemove = c("select2d","zoom2d","lasso2d", "drawclosedpath","drawopenpath", "hoverClosestCartesian","hoverCompareCartesian", "toggleHover","toggleSpikelines") ) ``` Fallecidos {.bg} ===================================== Column 1 {.tabset data-width=350} ------------------------------------- Column 1 {.tabset data-width=350} ------------------------------------- Column 1 {.tabset data-width=350} ------------------------------------- Fallecidos Nuevos {.bg} ===================================== Diagnósticos {.bg} ===================================== Diagnósticos Nuevos {.bg} =====================================